// pages/jiuba/jiuba.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight:0,
    isChecked:false,
    back:"",
    indicatorDots: false,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    circular:true,
    banner:[],
    cate:[],
    product:[],
    goods_num:[],
    userInfo:{},
    total:0,
    // 购物车里商品列表和对应的数目
    goodList:[],
    allNum:0,
    cartidList:[],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var scroll = this
    // 获取手机信息 确定scrollview的高度
    wx.getSystemInfo({
      success: function(res) {
        var height = res.screenHeight;
        var width = res.screenWidth;
        var scrollHeight = height - 65 - width / 750 * 500
        if(height == 812){
          var scrollHeight = height - 85 - width / 750 * 500
        }
        scroll.setData({
          scrollHeight:scrollHeight
        })
      },
    });

    // 回调函数获取userInfo
    if (app.globalData.userInfo){
      this.setData({
        userInfo: app.globalData.userInfo,  
      })
      console.log("1")
      var that = this;
      // app.getUser获取userInfo
        app.getUser(function (res) {
          var openid = app.globalData.openid;
          var nickname = app.globalData.userInfo.nickName;
          var gender = app.globalData.userInfo.gender;
          var headurl = app.globalData.userInfo.avatarUrl;
          //获取m_id
          wx.request({
            url: app.globalData.yuming + 'index.php/Api/Login/login',
            data: {
              openid: openid,
              nickname: nickname,
              gender: gender,
              headurl: headurl
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
              app.globalData.m_id = res.data.data.m_id
              // 获取购物车总价
              app.getTotal(res.data.data.m_id, function (data) {
                var total = data.data.data.total;
                if (total == null) {
                  total = 0
                }
                that.setData({
                  total: total
                })
              })
              //获取各商品的数量
              that.getList(app.globalData.m_id, function (data) {
                var list = [];
                var allNum = 0;
                for (var index in data) {
                  var array = {};
                  array.title = data[index].title;
                  array.num = data[index].num;
                  array.cartid = data[index].cart_id;
                  allNum = allNum + parseInt(data[index].num)
                  list.push(array)
                }
                app.globalData.goodList = list
                that.setData({
                  goodList: list,
                  allNum: allNum
                })
              })
            }
          })
        })      
    }else{
      var that = this
      app.userInfoReadyCallback = res => {
         // 获取用户m_id app.getUser 回调函数获取openid
        app.getUser(function(res){
          var openid = app.globalData.openid;
          var nickname = app.globalData.userInfo.nickName;
          var gender = app.globalData.userInfo.gender;
          var headurl = app.globalData.userInfo.avatarUrl;
          wx.request({
            url: app.globalData.yuming + 'index.php/Api/Login/login',
            data: {
              openid: openid,
              nickname: nickname,
              gender: gender,
              headurl: headurl
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
              app.globalData.m_id = res.data.data.m_id
              // 获取购物车总价
              app.getTotal(res.data.data.m_id,function(data){
                var total = data.data.data.total;
               if(total == null){
                  total =0;
               }
               that.setData({
                 total:total
               })
              })
              //获取各商品的数量
              that.getList(app.globalData.m_id, function (data) {
                var list = [];
                var allNum = 0;
                for (var index in data){                
                  var array = {};
                  array.title = data[index].title;
                  array.num = data[index].num;
                  array.cartid = data[index].cart_id;
                  allNum = allNum + parseInt(data[index].num)
                  list.push(array)
                }
                app.globalData.goodList = list
                that.setData({
                  goodList:list,
                  allNum:allNum
                })
              })
            }
          })
        })  
      }  
    }
    this.start();
  // 检查版本更新
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })

    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '更新失败，请检查网络设置！！',
        success: function (res) {
          
        }
      })
    })



  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //获取各商品的数量
    this.getList(app.globalData.m_id, function (data) {
      var list = [];
      var allNum = 0;
      for (var index in data) {
        var array = {};
        array.title = data[index].title;
        array.num = data[index].num;
        array.cartid = data[index].cart_id;
        allNum = allNum + parseInt(data[index].num)
        list.push(array)
      }
      app.globalData.goodList = list;
      that.setData({
        goodList: list,
        allNum: allNum
      })
    })
    // 获取总价
    app.getTotal(app.globalData.m_id, function (data) {
      var total = data.data.data.total;
      if (total == null) {
        total = 0
      }
      that.setData({
        total: total
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '众享通赢',
      path: ''
    }
  },
  // 列出所有的商品
  start:function(){
    var that = this;
    // 初始化列表
    wx.request({
      url: app.globalData.yuming + 'index.php/Api/Product/index',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      method: "GET",
      success: function (res) {
        var banner = res.data.data.banner || [];
        var cate = res.data.data.cate || [];
        var product = res.data.data.product || [];
        var length = product.length;
        var goods_num = []
        for (var i = 0; i < length; i++) {
          goods_num.push(0)
        }
        that.setData({
          banner: banner,
          cate: cate,
          product: product,
          goods_num: goods_num
        });
      }
    })
  },
// 添加到购物车
  addToCart:function(e){
    var p_id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var m_id = app.globalData.m_id;
    var that = this;
    wx.request({
      url: app.globalData.yuming +'index.php/Api/Cart/addCart',
      data: {
        m_id: m_id,
        p_id: p_id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method:"POST",
      success: function (res) {
        //返回的是cart_id，这里没有使用
        // 获取商品总价
        app.getTotal(app.globalData.m_id,function(data){
          var total = data.data.data.total;
          if (total == null) {
            total = 0
          }
          
          that.setData({
            total: total
          })
        })
        // 获取各个商品的数量,对应的cart_id以及购物车总数
        that.getList(app.globalData.m_id, function (data) {
          var list = [];
          var allNum = 0;
          for (var index in data) {
            var array = {};
            array.title = data[index].title;
            array.num = data[index].num;
            array.cartid = data[index].cart_id;
            allNum = allNum + parseInt(data[index].num);
            list.push(array);
          }
          app.globalData.goodList = list
          that.setData({
            goodList: list,
            allNum: allNum
          })
        })
      }

    })
  },
  // 删除商品
  removeToCart(e){
    var that = this;
    var cartid = e.currentTarget.dataset.cart;
    wx.request({
      url: app.globalData.yuming +'index.php/Api/Cart/editCart',
      data:{
        cart_id:cartid,
        type:2
      },
      header:{
        "content-type":'application/x-www-form-urlencoded'
      },
      method:"POST",
      success:function(res){
        // 返回商品总价
        app.getTotal(app.globalData.m_id, function (data) {
          var total = data.data.data.total;
          if (total == null) {
            total = 0
          };
          that.setData({
            total: total
          })
        })
        // 获取各个商品的数量,对应的cart_id以及购物车总数
        that.getList(app.globalData.m_id, function (data) {
          var list = [];
          var allNum = 0;
          for (var index in data) {
            var array = {};
            array.title = data[index].title;
            array.num = data[index].num;
            array.cartid = data[index].cart_id;
            allNum = allNum + parseInt(data[index].num);
            list.push(array);
          }
          app.globalData.goodList = list
          that.setData({
            goodList: list,
            allNum: allNum
          })
        })
      }
    })
  },
  // 获取购物车列表，对应商品名称及数量
  getList(m_id,callBack){
      wx.request({
        url: app.globalData.yuming +'index.php/Api/Cart/cartList',
        data:{
          m_id:m_id,
          p:1
        },
        header:{
          'content-type':'application/x-www-form-urlencoded'
        },
        method:"POST",
        success:function(res){
          var data = res.data.data;
          callBack(data)
        }
      })
  },
  // 改变列表
  change:function(e){
    // 改变列表样式（选中）
    var index = e.currentTarget.dataset.idx;
    var cate = this.data.cate.map(function(val){
         val['select'] = false;
         return val;
       });
       cate[index]['select'] = true;
    this.setData({
      cate: cate
    })
    var that = this;
    var cate_id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.yuming +'index.php/Api/Product/productList',
      data: {
        cate_id:cate_id,
        p:1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method:"POST",
      success: function (res) {
        var product = res.data.data;
        that.setData({
          product: product,
        });
      }
    })
    
  },
  // 跳转至订单页面
  switchTo:function(){
    var num = this.data.allNum;
    if(num == 0){
      wx.showModal({
        title:"提示",
        content:"您还没有选择任何商品",
        showCancel:false,
        success:function(){

        }
      })
    }else{
      wx.navigateTo({
        url: '../sure/sure'
      })
    }
    
  },
})